var express = require('express');
var router = express.Router();
var nodemailer = require('nodemailer');
var db = require('../public/javascripts/db');
var crypto = require('crypto');

var transporter = nodemailer.createTransport({
    service: 'qq',
    auth: {
        user: '1871518428@qq.com',
        pass: 'qucypixxcpdccddj'
    }
});

var code;

router.post('/', (req, res, next) => {
    console.log(req);
    code = parseInt(Math.random() * 90000 + 100000);

    var mailOptions = {
        from: '1871518428@qq.com',
        to: req.body.mail,
        subject: '验证码',
        html: `<h2>尊敬的用户您好:</h2><h3>您当前的验证码为` + code + `,该验证码一次有效。` +
        `<a href="http://blog.csdn.net/zzwwjjdj1/article/details/51878392">
    http://blog.csdn.net/zzwwjjdj1/article/details/51878392</a></h3>`
    }

    var sql = 'SELECT * FROM user WHERE mail = ?';
    db.query(sql, req.body.mail, (err, result) => {
        if (err) {
            throw err;
            return;
        } else {
            console.log('mail result', result);
            if (result.length == 0) {
                res.send('0');
                return;
            } else {
                transporter.sendMail(mailOptions, (err, info) => {
                    if (err) {
                        console.log(err);
                        return;
                    }
                    console.log('发送成功！');
                    res.send('2');
                    return;
                })
            }
        }
    })
})

router.put('/', (req, res, next) => {
    console.log(req.body);
    if (req.body.code != code) {
        res.send('0');
        return;
    }
    var modSql = 'UPDATE user SET password = ? WHERE mail = ?';
    var md5 = crypto.createHash('md5');
    var newPas = md5.update(req.body.password).digest('hex');
    var sql_params = [newPas, req.body.mail];
    db.query(modSql, sql_params, (err, result) => {
        if (err) {
            throw err;
            return;
        } else {
            console.log(result);
            res.send('2');
        }
    })
})

module.exports = router;